/*
 * FdStream.cpp
 *
 */

#include "FdStream.h"
#include <string.h>
#include <iostream>

IFdStream::IFdStream() {
	file = NULL;
	isOpen = false;
}

IFdStream::IFdStream(int fd) {
	open(fd);
}

IFdStream::~IFdStream() {
	if (isOpen)
		fclose(file);
}

void IFdStream::open(int fd) {
	file = fdopen(fd, "rb");
	if (file == NULL)
		isOpen = false;
	else
		isOpen = true;
}

void IFdStream::close() {
	if (isOpen)
		fclose(file);
}

bool IFdStream::is_open() const {
	return isOpen;
}

char IFdStream::read() {
	return fgetc(file);
}

size_t IFdStream::read(char* dest, size_t size) {
	size_t read = 0;
	if (isOpen)
		read = fread(dest, 1, size, file);
	return read;
}

//
// OFdStream
//

OFdStream::OFdStream() {
	file = NULL;
	isOpen = false;
}

OFdStream::OFdStream(int fd) {
	open(fd);
}

OFdStream::~OFdStream() {
	if (isOpen)
		fclose(file);
}

void OFdStream::open(int fd) {
	file = fdopen(fd, "wb");
	if (file == NULL)
		isOpen = false;
	else
		isOpen = true;
}

void OFdStream::close() {
	if (isOpen)
		fclose(file);
}

bool OFdStream::is_open() const {
	return (file != NULL);
}

void OFdStream::write(const std::string& str) {
	write(str.data(), str.length());
}

void OFdStream::write(char character) {
	fputc(character, file);
	fflush(file);
}

void OFdStream::write(const char* data, size_t size) {
	size_t sent = 0;
	while (sent < size) {
		sent += fwrite(&data[sent], 1, size - sent, file);
	}
	fflush(file);
}
